#include "stdafx.h"
#include "Carrot.h"


CCarrot::CCarrot()
{
	m_HP = 50;
}


CCarrot::~CCarrot()
{
}

void CCarrot::LoadImg(IplImage * pimgs[])
{ 
	for (int i = 0; i < CARROT_IMG_COUNT; i++)
	{ 
		m_image[i] = pimgs[i];
	}
}

void CCarrot::Release()
{
	/*for (int i = 0; i < CARROT_IMG_COUNT; i++)
	{
		cvReleaseImage(&m_image[i]);
	}*/
}

void CCarrot::DrawtoBK(IplImage * pbk)
{
	if (m_beginCounter > m_currentCounter)
		return;

	if (m_state >= CARROT_IMG_COUNT)
		return;
	if (pbk == NULL || m_image[m_state] == NULL)
		return;

	cvLine(pbk, CvPoint(m_pos.x , m_pos.y - 34),
		CvPoint(m_pos.x + m_HP, m_pos.y - 34),
		CvScalar(0, 0, 255), 3);

	for (int i = 0; i < m_image[m_state]->height; i++)
	{
		for (int j = 0; j < m_image[m_state]->width; j++)
		{
			 
			int srcr, srcg, srcb;
			srcb = CV_IMAGE_ELEM(m_image[m_state], uchar, i, j * 3 + 0);
			srcg = CV_IMAGE_ELEM(m_image[m_state], uchar, i, j * 3 + 1);
			srcr = CV_IMAGE_ELEM(m_image[m_state], uchar, i, j * 3 + 2);
			if ((srcg > 240) && (srcb < 20) && (srcr < 20))
				continue;

			int y = m_pos.y - m_image[m_state]->height + 32;

			if ((y + i) > pbk->height||(y + i)< 0)
				continue;
		 
			if ((m_pos.x + j) > pbk->width || (m_pos.x + j)< 0)
				continue;

			CV_IMAGE_ELEM(pbk, uchar, y + i, (j + m_pos.x) * 3 + 0) = srcb;
			CV_IMAGE_ELEM(pbk, uchar, y + i, (j + m_pos.x) * 3 + 1) = srcg;
			CV_IMAGE_ELEM(pbk, uchar, y + i, (j + m_pos.x) * 3 + 2) = srcr;

		}
	}
}

void CCarrot::InitPos(CvPoint bpos, int begincounter)
{
	m_beginCounter = begincounter;
	m_dir = -1;
	m_pos.x = bpos.x * 32;
	m_pos.y = bpos.y * 32;
	m_state = 0;
}

void CCarrot::Move(int dir, int curcount)
{
	m_currentCounter = curcount;
	if (m_beginCounter > m_currentCounter)
		return;

	m_dir = dir;
	m_state++;
	if (m_state >= CARROT_IMG_COUNT)
		m_state = 0;
	switch (dir)
	{
	case 0:
		m_pos.y -= 4;
		break;
	case 1:
		m_pos.y += 4;
		break;
	case 2:
		m_pos.x -= 4;
		 
		break;
	case 3:
		m_pos.x += 4;
		 
	}
}
 
